package com.graduation.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.model.R;
import com.graduation.ucenter.mapper.AuthorityMapper;
import com.graduation.ucenter.mapper.RoleMapper;
import com.graduation.ucenter.model.po.Authority;
import com.graduation.ucenter.model.po.Role;
import com.graduation.ucenter.service.AuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 小何
 * @Description: TODO
 * @DateTime: 2023/10/31 15:05
 **/
@Service
public class AuthorityServiceImpl extends ServiceImpl<AuthorityMapper, Authority> implements AuthorityService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AuthorityService authorityService;

    @Override
    public R<List<Authority>> listAuthority(Integer page, Integer pageSize, Authority authority) {
        LambdaQueryWrapper<Authority> qw = new LambdaQueryWrapper<>();
        if (authority != null) {
            qw.like(authority.getDescription() != null && !"".equals(authority.getDescription()), Authority::getDescription, authority.getDescription())
                    .like(authority.getName() != null && !"".equals(authority.getName()), Authority::getName, authority.getName())
                    .eq(authority.getId() != null, Authority::getId, authority.getId());
        }
        Page<Authority> authorityPage = new Page<>(page, pageSize);
        this.page(authorityPage, qw);
        Map<String, Object> map = new HashMap<>();
        map.put("count", authorityPage.getTotal());
        return R.success(authorityPage.getRecords(), map);
    }

    @Override
    public R<String> addAuthority(Authority authority) {
        //1.判断是否权限是否已存在
        LambdaQueryWrapper<Authority> qw = new LambdaQueryWrapper<>();
        qw.eq(authority != null && authority.getName() != null && !"".equals(authority.getName())
                , Authority::getName, authority.getName());
        Authority one = this.getOne(qw);
        if (one != null) {
            return R.error("已存在该权限");
        }
        this.save(authority);
        return R.success("权限添加成功");
    }

    @Override
    @Transactional
    public R<String> removeAuthorityAndBindRole(Integer authorityId) {
        //1.删除角色权限关联信息
        roleMapper.removeBindRoleId(authorityId);
        //2.删除权限信息
        authorityService.removeById(authorityId);
        return R.success("删除成功");
    }
}
